var md5 = require('../lib/md5.js');

//验证手机号码
function check_mobile (mobile) {
  if (!(/^1[3-9]\d{9}$/.test(mobile))) {
    return false;
  } else {
    return true;
  }
}

//验证金额
function check_money(money) {
  if (!(/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money))) {
    return false;
  } else {
    return true;
  }
}

//输入金额时时验证
function check_money_in (money) {
  if (!(/(^[1-9]([0-9]+)?(\.[0-9]{0,2})?$)|(^(0){1}$)|(^[0-9]\.([0-9]){0,2}?$)/.test(money))) {
    return false;
  } else {
    return true;
  }
}

//金额js取值优化（防止出现多位小数）
function money_opt(money) {
  money = parseFloat(money);
  money = Math.round(money * 100) / 100;
  return money;
}

//验证人名
function check_name(name) {
  /**
   *  可验证少数民族 /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/
   */
  if (!(/^[\u4E00-\u9FA5\uf900-\ufa2d]{2,10}$/.test(name))) {
    return false;
  } else {
    return true;
  }
}

//产品信息处理
function formatShop(front_url, products){
  for (var i in products) {
    let item = products[i];

    //item['Products_Name'] = item['Products_Name'].substring(0, 13);
    //是否是拼团产品
    item['pintuan_show'] = false;
    if (item['pintuan_flag'] == 1 && item['pintuan_end_time'] > parseInt(new Date().getTime() / 1000) && item['pintuan_people'] >= 2) {
      item['pintuan_show'] = true;
      item['discount'] = (item['Products_PriceX'] / item['Products_PriceY']).toFixed(2) * 10;
      item['discount'] = item['discount'].toPrecision(2);
    }

    item.Products_JSON = typeof item.Products_JSON != 'object' && item.Products_JSON != '' ? JSON.parse(item.Products_JSON) : item.Products_JSON;
    for (var j in item.Products_JSON.ImgPath) {
      item.Products_JSON.ImgPath[j] = item.Products_JSON.ImgPath[j] ? img_path(front_url, item.Products_JSON.ImgPath[j]) : '../../images/no_pic.png';
    }
    item.ImgPath = item.Products_JSON.ImgPath[0] ? item.Products_JSON.ImgPath[0] : '../../images/no_pic.png';

    item.skujosn = item.skujosn ? (typeof item.skujosn != 'object' && item.skujosn != '' ? JSON.parse(item.skujosn) : item.skujosn) : '';
    item.skuvaljosn = item.skuvaljosn ? (typeof item.skuvaljosn != 'object' && item.skuvaljosn != '' ? JSON.parse(item.skuvaljosn) : item.skuvaljosn) : '';
    for (var j in item.skuvaljosn) {
      item.skuvaljosn[j].Attr_Image = typeof item.skuvaljosn[j].Attr_Image == 'undefined' || item.skuvaljosn[j].Attr_Image == '' ? item.Products_JSON.ImgPath[0] : img_path(front_url, item.skuvaljosn[j].Attr_Image);
    }

    //产品保障处理
    item.Products_Promise = item.Products_Promise ? (typeof item.Products_Promise != 'object' ? JSON.parse(item.Products_Promise) : item.Products_Promise) : '';
    for (var j in item.Products_Promise) {
      if (item.Products_Promise[j].name == '') {
        item.Products_Promise.splice(j, 1);
      }
    }

    products[i] = item;
  }
  return products;
}

//购物车产品处理
function cart_pro (productsList, action) {
  if (action && action == 'Qty') {  //获取购物车产品总数量
    var Qty = 0;
    for (var i in productsList) {
      for (var j in productsList[i]) {
        Qty += parseInt(productsList[i][j]['Qty']);
      }
    }
    return Qty > 0 ? Qty : 0;
  } else {  //产品信息处理
    for (var i in productsList) {
      for (var j in productsList[i]) {
        
      }
    }
    return productsList
  }
}

//图片路径处理
function img_path(front_url, ImgPath) {
  if (ImgPath && ImgPath != '' && ImgPath.indexOf('http') == -1) { //判断不为空且不为网络图片
    if (ImgPath.indexOf('/api/') > -1 && ImgPath.indexOf('/static/api/') == -1) {  //轮播图为原始数据
      ImgPath = front_url + '/static' + ImgPath;
    } else {
      ImgPath = front_url + ImgPath;
    }
  } else if (ImgPath == '') {
    ImgPath = '../../images/none.png';
  }
  return ImgPath;
}

//订单图片加载错误使用默认图片(二维产品列表处理（不含属性）)  index、search页面
function show_default_OrderImg(orderlist, proid,attrid) {
  for (var i in orderlist) {
    for (var j in orderlist[i]['Order_CartList']){
      for (var k in orderlist[i]['Order_CartList'][j]){}
      if (j == proid && k == attrid) {
        orderlist[i]['Order_CartList'][j][k]['ImgPath'] = '../../images/no_pic.png';
      }
    }
  }
  return orderlist;
}

//产品图片加载错误使用默认图片(二维产品列表处理（不含属性）)  index、search页面
function show_default_proImg (productsList, proid) {
  for (var i in productsList) {
    if (productsList[i]['Products_ID'] == proid) {
      productsList[i]['ImgPath'] = '../../images/no_pic.png';
    }
  }
  return productsList;
}

//商家图片加载错误使用默认图片(二维产品列表处理（不含属性）)  index、search页面
function show_default_BizImg (bizlist, bizid) {
  for (var i in bizlist) {
    if (bizlist[i]['Biz_ID'] == bizid) {
      bizlist[i]['Biz_Logo'] = '../../images/no_pic.png';
    }
  }
  return bizlist;
}

//产品banner图片加载错误使用默认图片(二维产品列表处理（不含属性）)  index、search页面
function show_default_ProBannerImg(productDetail, proid) {
  if (productDetail['Products_ID'] == proid) {
    productDetail['Biz_Logo'] = '../../images/no_pic.png';
    for (var i in productDetail['Products_JSON']['ImgPath']) {
      productDetail['Products_JSON']['ImgPath'][i] = '../../images/no_pic.png';
    }
  }
  return productDetail;
}

//评论图片加载错误使用默认图片(二维产品列表处理（不含属性）)  index、search页面
function show_default_ComImg(Biz_Commit, proid) {
  for (var i in Biz_Commit) {
    if (Biz_Commit[i]['Product_ID'] == proid) {
      for (var j in Biz_Commit[i]['ImgPath']) {
        Biz_Commit[i]['ImgPath'][j] = '../../images/no_pic.png';
      }
    }
  }
  return Biz_Commit;
}

//产品图片加载错误使用默认图片(三维产品列表处理（含属性）)  cart页面
function show_default_proImg_cart(productsList, proid, attrid) {
  for (var i in productsList) {
    for (var j in productsList[i]) {
      if (i == proid && j == attrid) {
        productsList[i][j]['ImgPath'] = '../../images/no_pic.png';
      }
    }
  }
  return productsList;
}

//订单列表订单信息处理
function formatOrder(front_url, orderlist) {
  if (!orderlist || orderlist == '') return orderlist;
  
  for (var i in orderlist) {
    orderlist[i]['Order_CreateTime'] = formatDate(orderlist[i]['Order_CreateTime']);
    orderlist[i]['Pay_time'] = formatDate(orderlist[i]['Pay_time']);
    orderlist[i]['Order_Shipping'] = orderlist[i]['Order_Shipping'] ? JSON.parse(orderlist[i]['Order_Shipping']) : '';
    orderlist[i]['Property'] = JSON.parse(orderlist[i]['Property']);
    var CartList = orderlist[i]['Order_CartList'] = orderlist[i]['Order_CartList'] ? JSON.parse(orderlist[i]['Order_CartList']) : '';
    orderlist[i].Products_IsPaysBalance = 1;
    if (CartList != '') {
      for (var pro_id in CartList) {
        for (var attr_id in CartList[pro_id]) {
          var ImgPath = CartList[pro_id][attr_id]['ImgPath'];
          CartList[pro_id][attr_id]['ImgPath'] = !ImgPath ? '/images/no_pic.png' : (ImgPath.indexOf('http') > -1 || ImgPath.indexOf('/uploadfiles/') == -1 ? ImgPath : front_url + ImgPath);
          CartList[pro_id][attr_id].IsBackShop = typeof CartList[pro_id][attr_id].IsBackShop != 'undefined' ? CartList[pro_id][attr_id].IsBackShop : 1;

          if (orderlist[i].Products_IsPaysBalance && (typeof CartList[pro_id][attr_id].Products_IsPaysBalance == 'undefined' || CartList[pro_id][attr_id].Products_IsPaysBalance != 1)) {
            orderlist[i].Products_IsPaysBalance = 0;
          }
        }
      }
    }

    if (orderlist[i].back_order) {
      orderlist[i].back_order = formatbackorder(front_url, orderlist[i].back_order);
    }
  }
  return orderlist;
}

// 退款单处理
function formatbackorder(front_url, orderlist) {
  for (var j in orderlist) {
    var back_detail = orderlist[j];

    orderlist[j].Back_CreateTime = formatDate(orderlist[j].Back_CreateTime);
    orderlist[j].Back_UpdateTime = orderlist[j].Back_UpdateTime > 0 ? formatDate(orderlist[j].Back_UpdateTime) : 0;
    var back_CartList = back_detail['Back_Json'] = back_detail['Back_Json'] ? JSON.parse(back_detail['Back_Json']) : '';
    if (back_CartList != '') {
      if (back_detail.ProductID > 0) {  // 单产品  back_CartList:只保留产品信息  ProductID：产品id  Back_CartID：产品属性id
        back_CartList['ImgPath'] = !back_CartList.ImgPath ? '/images/no_pic.png' : (back_CartList.ImgPath.indexOf('http') > -1 || back_CartList.ImgPath.indexOf('/uploadfiles/') == -1 ? back_CartList.ImgPath : front_url + back_CartList.ImgPath);
      } else {
        for (var pro_id in back_CartList) {
          for (var attr_id in back_CartList[pro_id]) {
            var ImgPath = back_CartList[pro_id][attr_id]['ImgPath'];
            back_CartList[pro_id][attr_id]['ImgPath'] = !ImgPath ? '/images/no_pic.png' : (ImgPath.indexOf('http') > -1 || ImgPath.indexOf('/uploadfiles/') == -1 ? ImgPath : front_url + ImgPath);
          }
        }
      }
    }
    // 退款上传图片
    var Refund_Image = orderlist[j].Refund_Image ? orderlist[j].Refund_Image.split(',') : '';
    for (var k in Refund_Image) {
      Refund_Image[k] = Refund_Image[k].indexOf('http') > -1 ? Refund_Image[k] : front_url + Refund_Image[k];
    }
    orderlist[j].Refund_Image = Refund_Image;

    // 退单记录
    for (var k in orderlist[j].back_detail) {
      orderlist[j].back_detail[k].createtime = formatDate(orderlist[j].back_detail[k].createtime);
    }
  }

  return orderlist;
}

/**
 * 处理用户列表中的时间
 */
function formatUserList(userlist, front_url) {
  if (!userlist || userlist == '') return userlist;
  for (var i in userlist) {
    userlist[i]['User_CreateTime'] = formatDate(userlist[i]['User_CreateTime']);
    userlist[i]['User_NickName'] = userlist[i]['User_NickName'] ? userlist[i]['User_NickName'] : '暂无昵称';
    userlist[i]['User_Mobile'] = userlist[i]['User_Mobile'] ? userlist[i]['User_Mobile'] : '暂未设置';
    userlist[i]['User_HeadImg'] = userlist[i]['User_HeadImg'] ? (userlist[i]['User_HeadImg'].indexOf('http') > -1 ? userlist[i]['User_HeadImg'] : front_url + userlist[i]['User_HeadImg']) : '../../images/moren.png';
  }
  return userlist;
}

/**
 * 格式化时间
 * 目前支持格式 ：2017-10-12
 */
function formatDate(mtime) {  
  mtime = new Date(parseInt(mtime) * 1000);
  return mtime.getFullYear() + '/' + (mtime.getMonth() + 1) + '/' + mtime.getDate() + ' ' + mtime.getHours() + ':' + mtime.getMinutes() + ':' + mtime.getSeconds(); 
}

/**
 * 格式化时间
 */
function formatTime(format_str,mtime) {
  if (!mtime) {
    var mtime = new Date();
  } else {
    var mtime = new Date(parseInt(mtime) * 1000);
  }   
  var timeObject = {
    "M+": mtime.getMonth() + 1,                   //月份 
    "d+": mtime.getDate(),                        //日 
    "h+": mtime.getHours(),                       //小时 
    "m+": mtime.getMinutes(),                     //分 
    "s+": mtime.getSeconds(),                     //秒 
    "q+": Math.floor((mtime.getMonth() + 3) / 3), //季度 
    "S": mtime.getMilliseconds()                  //毫秒 
  };
  if (/(y+)/.test(format_str)) {
    format_str = format_str.replace(RegExp.$1, (mtime.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in timeObject) {
    if (new RegExp("(" + k + ")").test(format_str)) {
      format_str = format_str.replace(RegExp.$1, (RegExp.$1.length == 1) ? (timeObject[k]) : (("00" + timeObject[k]).substr(("" + timeObject[k]).length)));
    }
  }
  return format_str;
} 
/**
 * 数组排序（值为number型）
 * arr 需要排序的数组
 * order_by   desc: 降续排列  asc: 升续排列
 * 默认为asc
 */
function number_sort (arr, order_by) {
  if (typeof order_by != 'undefined' && order_by == 'desc') { //desc
    return arr.sort(function (v1, v2) { return v2 - v1; });
  } else {  //asc
    return arr.sort(function (v1, v2) { return v1 - v2; });
  }
}

//数组转化
function array_change (arr, default_cloumn = '') {
  var array = default_cloumn == '' ? [] : [default_cloumn];
  for (var i in arr) {
    array.push({'id': i, 'name': arr[i]});
  }
  return array;
}

//获取数组下标  用于收货地址选择的显示
function get_arr_index (arr, id) {
  for (var i in arr) {
    if (arr[i]['id'] == id) {
      return i;
    }
  }
}

//创建随即字符串
function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 30; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

// 生成统一下单签名
function paysignjsapi(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, key) {
  var ret = {
    appid: appid,
    body: body,
    mch_id: mch_id,
    nonce_str: nonce_str,
    notify_url: notify_url,
    openid: openid,
    out_trade_no: out_trade_no,
    spbill_create_ip: spbill_create_ip,
    total_fee: total_fee,
    trade_type: 'JSAPI'
  };
  var str = raw(ret);
  str = str + '&key=' + key;
  var md5Str = md5.hexMD5(str).toUpperCase();
  return md5Str;
}

function raw(args) {
  var keys = Object.keys(args);
  keys = keys.sort();
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });

  var str = '';
  for (var k in newArgs) {
    str += '&' + k + '=' + newArgs[k];
  }
  str = str.substr(1);
  return str;
}


//生成微信支付签名
function paysignjs(appid, nonceStr, wxpayPackage, signType, timeStamp, key) {
  var ret = {
    appId: appid,
    nonceStr: nonceStr,
    package: wxpayPackage,
    signType: signType,
    timeStamp: timeStamp
  };
  var str = raw1(ret);
  str = str + '&key=' + key;
  return md5.hexMD5(str);
}

function raw1(args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key] = args[key];
  });

  var str = '';
  for (var k in newArgs) {
    str += '&' + k + '=' + newArgs[k];
  }
  str = str.substr(1);
  return str;
}


/* 毫秒级倒计时 */
function count_down(that, i) {
  var teamsList = that.data.teamsList;
  //计算剩余时间，拼团开始后（开团付款成功）24小时不能拼团成功，则为失败
  var team_last_time = teamsList[i].addtime * 1000 + (24 * 60 * 60 * 1000) - (new Date().getTime());
  if (team_last_time <= 0) {
    wx.showModal({
      title: '提示',
      content: '该团时间已到，不能参团',
      showCancel: false,
      success: function () {
        wx.navigateBack({
          delta: 1
        });
      }
    });
  } else {
    // 渲染倒计时时钟
    teamsList[i]['clock'] = date_format(team_last_time);
    that.setData({
      teamsList: teamsList
    });

    setTimeout(function () {
      // 放在最后--
      count_down(that, i);
    }, 1000)
  }
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second, is_show_day = 0) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;

  // 天
  var day = 0;
  if (is_show_day) {
    day = Math.floor(hr / 24);
    hr -= day * 24;
  }

  return (day > 0 ? day + '天 ' : '') + hr + ":" + min + ":" + sec;
  // 毫秒位，保留2位
  //var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  //return (day > 0 ? day + ' 天 ' : '') + hr + ":" + min + ":" + sec + " " + micro_sec;
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

//格式化金额
function format_money(money,mtype = 1) {
    var strs = [];
    strs = String(money).split('.');
    var length = strs.length;
    var str = '';
    if (mtype == 1) {
      str = strs[0];
    } else {
      if (length>1) {
        switch (strs[1].length) {
          case 1:
            str = strs[1] + '0';
            break;
          case 2:
            str = strs[1];
            break;
          default:
            str = String(Math.round(strs[1] / 100)).substring(0, 2);
        }
      } else {
        str = '00';
      }      
    }
  return str;

}

/**
 * 替换字符串当中字符为*
 */
function replace_str(str, replace = '***') {
  var length = str.length;
  if (length < 7) {
    return str;
  }
  return str.substring(0, 3) + replace + str.substring(length - 3, length);
}

/**
 * 计算会员折扣价格并且判断产品价格是否小于0.01*
 */
function judge_price(price, curagio) {
  price = Math.round(price * (1 - curagio / 100) * 100) / 100;
  if (price < 0.01) {
        price = 0.01;
  }
  return price;
}

//  结束下拉刷新
function overPullDownRefresh() {
  wx.hideLoading();
  wx.hideNavigationBarLoading();
  wx.stopPullDownRefresh();
}

// 判断字符串是否可解析成json对象
function isJsonString(str) {
  try {
    if (typeof JSON.parse(str) == "object") {
      return true;
    }
  } catch (e) {
  }
  return false;
}

module.exports = {
  formatShop: formatShop,
  judge_price: judge_price,
  cart_pro: cart_pro,
  img_path: img_path,
  show_default_proImg: show_default_proImg,
  show_default_BizImg: show_default_BizImg,
  show_default_ProBannerImg: show_default_ProBannerImg,
  show_default_ComImg: show_default_ComImg,
  show_default_OrderImg: show_default_OrderImg,
  formatOrder: formatOrder,
  formatbackorder: formatbackorder,
  number_sort: number_sort,
  array_change: array_change,
  get_arr_index: get_arr_index,
  makeid: makeid,
  paysignjsapi: paysignjsapi,
  paysignjs: paysignjs,
  check_mobile: check_mobile,
  count_down: count_down,
  date_format: date_format,
  format_money: format_money,
  formatUserList: formatUserList,
  formatDate: formatDate,
  replace_str: replace_str,
  formatTime: formatTime,
  check_money: check_money,
  check_money_in: check_money_in,
  money_opt: money_opt,
  check_name: check_name,
  show_default_proImg_cart: show_default_proImg_cart,
  fill_zero_prefix: fill_zero_prefix,
  overPullDownRefresh: overPullDownRefresh,
  isJsonString: isJsonString
}